package com.jsbj.user.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsbj.base.ResultBean;
import com.jsbj.page.PageDomain;
import com.jsbj.page.TableSupport;
import com.jsbj.tools.*;
import com.jsbj.user.entities.SysDictData;
import com.jsbj.user.entities.SysDictDataVo;
import com.jsbj.user.entities.SysDictType;
import com.jsbj.user.entities.SysUser;
import com.jsbj.user.mapper.SysDictDataMapper;
import com.jsbj.user.service.ISysDictDataService;
import com.jsbj.user.service.ISysDictTypeService;
import com.jsbj.user.service.ISysUserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 字典类型数据表 服务实现类
 * </p>
 *
 * @author jsbj
 * @since 2022-03-07
 */
@Service
public class SysDictDataServiceImpl extends ServiceImpl<SysDictDataMapper, SysDictData> implements ISysDictDataService {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ISysDictTypeService sysDictTypeService;

    @Autowired
    private ISysUserService sysUserService;

    @Override
    public List<SysDictData> getDataByKey(String dictKey) {
        LambdaQueryWrapper<SysDictData> wrapper = new LambdaQueryWrapper();
        wrapper.eq(SysDictData::getDisabled, 0);
        wrapper.eq(SysDictData::getDictKey, dictKey);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public List<SysDictData> getDataByDictKey(HttpServletRequest request, String inParam) {
        JSONObject object = JSONObject.parseObject(inParam);
        String dictKey = (String) object.get("dictKey");
        String dicDesc = (String) object.get("dicDesc");
        LambdaQueryWrapper<SysDictData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictData::getDisabled, 0);
        if (StringUtils.isNotEmpty(dictKey)) {
            queryWrapper.eq(SysDictData::getDictKey, dictKey);
        }
        if (StringUtils.isNotEmpty(dicDesc)) {
            queryWrapper.like(SysDictData::getDicDesc, dicDesc);
        }
        queryWrapper.orderByAsc(SysDictData::getSort);
        List<SysDictData> list = baseMapper.selectList(queryWrapper);
        if (StringUtils.isNotEmpty(dictKey)) {
            LambdaQueryWrapper<SysDictType> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(SysDictType::getDisabled, 0);
            queryWrapper1.eq(SysDictType::getDictTypeKey, dictKey);
            queryWrapper1.last(" limit 1");
            SysDictType sysDictType = sysDictTypeService.getOne(queryWrapper1);
            if (null != sysDictType) {
                for (SysDictData sysDictData : list) {
                    sysDictData.setDictTypeDesc(sysDictType.getDictTypeDesc());
                }
            }
        }
        return list;
    }

    @Override
    public String selectDictDescByKeyAndValue(String dictKey, String dicValue) {
        LambdaQueryWrapper<SysDictData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictData::getDisabled, 0);
        queryWrapper.eq(SysDictData::getDictKey, dictKey);
        queryWrapper.eq(SysDictData::getDicValue, dicValue);
        queryWrapper.last(" limit 1 ");
        SysDictData data = baseMapper.selectOne(queryWrapper);
        if (null != data) {
            return data.getDicDesc();
        }
        return null;
    }

    @Override
    public SysDictData selectDictDataByKeyAndDesc(String dicKey, String dicDesc) {
        LambdaQueryWrapper<SysDictData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictData::getDisabled, 0);
        queryWrapper.eq(SysDictData::getDictKey, dicKey);
        queryWrapper.eq(SysDictData::getDicDesc, dicDesc);
        queryWrapper.last(" limit 1 ");
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public ResultBean<String> add(SysDictData sysDictData) {
        String userId = RequestHeaderUtils.getUserId(request);
        if (StringUtils.isEmpty(sysDictData.getDictKey()) || StringUtils.isEmpty(sysDictData.getDicDesc())) {
            return new ResultBean<>().build("必填项不能为空！");
        }
        // 校验数据dictkey是否存在，以及要添加的值是否存在
        List<SysDictType> dicKeys = sysDictTypeService.getByDicKeys(sysDictData.getDictKey());
        if (org.springframework.util.CollectionUtils.isEmpty(dicKeys)) {
            return new ResultBean<>().build("字典数据类型不存在！");
        }
        // 校验数据是否已存在
        LambdaQueryWrapper<SysDictData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictData::getDisabled, 0);
        queryWrapper.eq(SysDictData::getDicDesc, sysDictData.getDicDesc());
        queryWrapper.eq(SysDictData::getDictKey, sysDictData.getDictKey());
        if (null != sysDictData.getId()) {
            queryWrapper.ne(SysDictData::getId, sysDictData.getId());
        }
        List<SysDictData> exists = baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(exists)) {
            return new ResultBean<>().build("数据已存在！");
        }
        if (null == sysDictData.getId()) {
            sysDictData.setCreaterId(userId);
            sysDictData.setCreateTime(new Date());
            sysDictData.setUpdateId(userId);
            sysDictData.setUpdateTime(new Date());

            SysDictData maxKeyValues = baseMapper.selectMaxKey(sysDictData.getDictKey());
            int dicValue = 1;
            if (null != maxKeyValues) {
                dicValue = maxKeyValues.getDicValue() + 1;
            }
            sysDictData.setDicValue(dicValue);

            baseMapper.insert(sysDictData);
        } else {
            SysDictData sysDictData1 = baseMapper.selectById(sysDictData.getId());
            BeanUtils.copyPropertiesIgnoreNull(sysDictData, sysDictData1);
            sysDictData.setUpdateId(userId);
            sysDictData.setUpdateTime(new Date());
            baseMapper.updateById(sysDictData);
        }
        return new ResultBean<>().success("处理成功！");
    }

    @Override
    public Integer delete(String id) {
        String userId = RequestHeaderUtils.getUserId(request);
        SysDictData sysDictData = baseMapper.selectById(id);
        sysDictData.setDisabled(1);
        sysDictData.setUpdateId(userId);
        sysDictData.setUpdateTime(new Date());
        return baseMapper.updateById(sysDictData);
    }

    @Override
    public Integer deletePost(String id) throws Exception{
        String userId = RequestHeaderUtils.getUserId(request);
        SysDictData sysDictData = baseMapper.selectById(id);
        //判断岗位是否已经被引用，若被引用则不能删除
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getDisabled,0);
        wrapper.inSql(SysUser::getId,"select user_id from sys_user_post p JOIN sys_dict_data d on p.post_id=d.dic_value WHERE p.disabled = 0 and d.disabled=0 AND d.id='"+id+"'");
        List<SysUser> users = sysUserService.list(wrapper);
        if(users!=null && users.size()>0){
            throw new Exception("岗位已绑定用户，不能删除");
        }else{
            //删除
            sysDictData.setDisabled(1);
            sysDictData.setUpdateId(userId);
            sysDictData.setUpdateTime(new Date());
            return baseMapper.updateById(sysDictData);
        }

    }

    @Override
    public void export(String inParam, HttpServletResponse response) throws IOException {
        List<SysDictDataVo> collect = new ArrayList<>();
        List<SysDictData> sysDictDataList = getDataByDictKey(request, inParam);
        for (SysDictData sysDictData : sysDictDataList) {
            sysDictData.setCreateTimeStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, sysDictData.getCreateTime()));
        }
        if (CollectionUtils.isNotEmpty(sysDictDataList)) {
            collect = sysDictDataList.stream().map(var -> {
                SysDictDataVo vo = new SysDictDataVo();
                org.springframework.beans.BeanUtils.copyProperties(var, vo);
                return vo;
            }).collect(Collectors.toList());
        }
        Workbook workBook = ExcelExportUtil.exportExcel(new ExportParams(null, "字典数据详情表"),
                SysDictDataVo.class, collect);
        FileUtil.easypoiFileDownload(workBook, response, "字典数据详情表", "字典数据详情表");
    }

    @Override
    public List<SysDictData> getSecType() {
        LambdaQueryWrapper<SysDictData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictData::getDisabled, 0);
        queryWrapper.eq(SysDictData::getDictKey, "secType");
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public IPage<SysDictData> getList(String inParam) {
        JSONObject object = JSONObject.parseObject(inParam);
        String dictKey = (String) object.get("dictKey");
        String dicDesc = (String) object.get("dicDesc");
        LambdaQueryWrapper<SysDictData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictData::getDisabled, 0);
        if (StringUtils.isNotEmpty(dictKey)) {
            queryWrapper.eq(SysDictData::getDictKey, dictKey);
        }
        if (StringUtils.isNotEmpty(dicDesc)) {
            queryWrapper.like(SysDictData::getDicDesc, dicDesc);
        }
        queryWrapper.orderByAsc(SysDictData::getSort);
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPage();
        Integer pageSize = pageDomain.getPageSize();
        Page<SysDictData> page = new Page<>(pageNum, pageSize);
        IPage<SysDictData> iPage = baseMapper.selectPage(page, queryWrapper);

        if (StringUtils.isNotEmpty(dictKey)) {
            LambdaQueryWrapper<SysDictType> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(SysDictType::getDisabled, 0);
            queryWrapper1.eq(SysDictType::getDictTypeKey, dictKey);
            queryWrapper1.last(" limit 1");
            SysDictType sysDictType = sysDictTypeService.getOne(queryWrapper1);
            if (null != sysDictType) {
                for (SysDictData sysDictData : iPage.getRecords()) {
                    sysDictData.setDictTypeDesc(sysDictType.getDictTypeDesc());
                }
            }
        }
        return iPage;
    }

    @Override
    public List<SysDictData> getDataByKeyAndRemark(String dictKey, String systemCode) {
        LambdaQueryWrapper<SysDictData> wrapper = new LambdaQueryWrapper();
        wrapper.eq(SysDictData::getDisabled, 0);
        wrapper.eq(SysDictData::getDictKey, dictKey);
        wrapper.like(SysDictData::getRemark,systemCode);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public List<SysDictData> getOrgTypePageData() {
        String dictKey = "orgType";
        LambdaQueryWrapper<SysDictData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictData::getDisabled, 0);
        if (StringUtils.isNotEmpty(dictKey)) {
            queryWrapper.eq(SysDictData::getDictKey, dictKey);
        }
        queryWrapper.notIn(SysDictData::getDicValue, 1,2,4);
        queryWrapper.orderByAsc(SysDictData::getSort);
        List<SysDictData> list = baseMapper.selectList(queryWrapper);
        if (StringUtils.isNotEmpty(dictKey)) {
            LambdaQueryWrapper<SysDictType> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(SysDictType::getDisabled, 0);
            queryWrapper1.eq(SysDictType::getDictTypeKey, dictKey);
            queryWrapper1.last(" limit 1");
            SysDictType sysDictType = sysDictTypeService.getOne(queryWrapper1);
            if (null != sysDictType) {
                for (SysDictData sysDictData : list) {
                    sysDictData.setDictTypeDesc(sysDictType.getDictTypeDesc());
                }
            }
        }
        return list;
    }

    @Override
    public List<SysDictData> getDataByDictKeyOnly(String dictKey) {
        LambdaQueryWrapper<SysDictData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictData::getDisabled, 0);
        if (StringUtils.isNotEmpty(dictKey)) {
            queryWrapper.eq(SysDictData::getDictKey, dictKey);
        }
        queryWrapper.orderByAsc(SysDictData::getSort);
        List<SysDictData> list = baseMapper.selectList(queryWrapper);
        return list;
    }

    @Override
    public IPage<SysDictData> getPageDataByDictKey(HttpServletRequest request, String inParam) {
        JSONObject object = JSONObject.parseObject(inParam);
        String dictKey = (String) object.get("dictKey");
        String dicDesc = (String) object.get("dicDesc");
        LambdaQueryWrapper<SysDictData> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDictData::getDisabled, 0);
        if (StringUtils.isNotEmpty(dictKey)) {
            queryWrapper.eq(SysDictData::getDictKey, dictKey);
        }
        if (StringUtils.isNotEmpty(dicDesc)) {
            queryWrapper.like(SysDictData::getDicDesc, dicDesc);
        }
        queryWrapper.orderByAsc(SysDictData::getSort);
        /**
         * 分页条件
         */
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPage();
        Integer pageSize = pageDomain.getPageSize();
        Page<SysDictData> page = new Page<>(pageNum, pageSize);

        IPage<SysDictData> list = baseMapper.selectPage(page,queryWrapper);
        return list;
    }
}
